﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Compiler
{
    class Reduce : ParseTableAction
    {
        private Production production;
        private ParseTable parseTable;

        public Reduce(Production production, ParseTable parseTable)
        {
            this.production = production;
            this.parseTable = parseTable;
        }

        public void Execute(
            IEnumerator<LexerPair> sourceEnumerator, 
            Stack<Entry> stack,
            Stack<INode> nodeStack,
            INodeFactory nodeFactory)
        {
            if(!production.isEpsilonProduction())
                stack.Pop(production.Tail.Count);

            SimpleParseTableState z = stack.Peek().state;
            SimpleParseTableState followState;
            parseTable.GetJumptableState(z, production.Head, out followState);

            stack.Push(new Entry(followState, production.Head));

            if (nodeFactory != null)
            {
                var node = nodeFactory.OnNonterminal(production, nodeStack);
                if (node != null)
                    nodeStack.Push(node);
            }
        }

        public override string ToString()
        {
            return "r" + production.ID.ToString();// +"  (" + production.ToString() + ")";
        }
    }
}
